﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MINERP.DAL;
using MINERP.COM;
using MINERP.BLL.Common;
using MINERP.MODEL.FactoryTech;
using MINERP.DAL.FactoryTech;
using System.Data;

namespace MINERP.BLL.FactoryTech
{
    public class FactoryTechBLL
    {
        WorkFlowListBLL _wflBLL = new WorkFlowListBLL();
        FactoryTechDAL _dal = new FactoryTechDAL();
        /// <summary>
        /// 判断产品的下一节点是否工厂节点
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public bool IsNextFactryTech(int productId)
        {
            bool flag = false;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<WorkOrderFlowList> wflList = db.WorkOrderFlowList.Where(w => w.orderInfo.OrderProductId == productId).OrderBy(w=>w.WorkOrder).ToList();
                WorkOrderFlowList wfl = wflList.FirstOrDefault(w=>w.Status ==1);
                if(wfl!=null)//存在状态为1的节点
                {
                    for (int i = 0; i < wflList.Count; i++)
                    {
                        if (wfl.WorkFlowListId == wflList[i].WorkFlowListId)//当前所在节点
                        {
                            WorkOrderFlowList nextwfl = wflList[i + 1];
                            if (!nextwfl.tb_TechReference.IsLoaded)
                            {
                                nextwfl.tb_TechReference.Load();
                            }
                            if (nextwfl.tb_Tech.TechType == (int)TechType.Factory)//如果是工厂节点
                            {
                                flag = false;
                            }
                            else
                            {
                                flag = true;
                            }
                            break;
                        }
                    }
                }
                else 
                {
                    throw new Exception("产品已经完成！");
                }
                
            }
            return flag;
        }

        /// <summary>
        /// 完成流程
        /// </summary>
        /// <param name="techId"></param>
        /// <param name="userId"></param>
        /// <param name="orderproductId"></param>
        /// <returns></returns>
        public bool CompleteTech(int techId, int userId, string orderproductcode,Dictionary<int,string> oprates)
        {

            using (newSampleYPDBEntities db =new newSampleYPDBEntities())
            {
                orderInfo oi = db.orderInfo.FirstOrDefault(o=>o.OrderProductCode ==orderproductcode);
                if (oi != null)
                {
                    int commintUserID = userId;
                    WorkOrderFlowList wfl = db.WorkOrderFlowList.FirstOrDefault(w =>  w.orderInfo.OrderProductId == oi.OrderProductId && w.tb_Tech.TechId == techId);
                    if (wfl == null)
                    {
                        //WorkOrderFlowList wflAssigned = db.WorkOrderFlowList.FirstOrDefault(w => w.orderInfo.OrderProductId == oi.OrderProductId && w.tb_Tech.TechId == techId);
                        //users user = db.users.FirstOrDefault(u => u.userID == wflAssigned.UserId);
                        //if (user != null)
                        //{
                        //    throw new Exception("该产品任务已经被" + user.UserName + "接收");
                        //}
                        commintUserID = wfl.UserId;
                    }
                    return _wflBLL.OverCurTech(techId, commintUserID, oi.OrderProductId);
                }
                else
                {
                    throw new Exception("该产品号不存在！");
                }
                
 
            }
            
        }


        /// <summary>
        /// 接收任务
        /// </summary>
        /// <param name="techId"></param>
        /// <param name="userId"></param>
        /// <param name="orderproductcode"></param>
        /// <returns></returns>
        public int ReceiveTask(int techId, int userId, string orderproductcode)
        {
            int ret=0;

            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                WorkOrderFlowList wfl = db.WorkOrderFlowList.FirstOrDefault(w => w.orderInfo.OrderProductCode == orderproductcode && w.tb_Tech.TechId == techId);
                if (wfl != null)
                {
                    wfl.UserId = userId;
                }
                else
                {
                    ret = -1;
                }

                db.SaveChanges();
            }
            return ret;
        }


        /// <summary>
        /// 通过产品ID获得该产品的当前流程ID
        /// </summary>
        /// <param name="orderproductId"></param>
        /// <returns>0 产品不存在，-1 产品无流程或者流程已完成,-2 该产品当前流程不在相册厂工艺流程中</returns>
        public int GetCurrentTechIdByOrderProductId(string  orderproductcode,out string msg)
        {
            int ret;
            msg = "";
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductCode == orderproductcode);
                if (oi != null)//产品存在
                {
                    if (!oi.WorkOrderFlowList.IsLoaded)
                    {
                        oi.WorkOrderFlowList.Load();
                    }
                    WorkOrderFlowList wfl = oi.WorkOrderFlowList.FirstOrDefault(w => w.Status == 1);
                    if (wfl != null)
                    {
                        if (!wfl.tb_TechReference.IsLoaded)
                        {
                            wfl.tb_TechReference.Load();
                        }
                        if (wfl.tb_Tech.TechType == (int)TechType.Factory)//该产品当前流程在相册厂工艺流程中
                        {
                            ret = wfl.tb_Tech.TechId;
                        }
                        else//该产品当前流程不在相册厂工艺流程中
                        {
                            ret = -2;
                            msg = "该产品当前流程在："+wfl.tb_Tech.TechName;
                        }
                       
                    }
                    else//产品无流程或者流程已完成
                    {
                        ret = -1;
                    }
                }
                else//产品不存在
                {
                    ret = 0;
                }
            }

            return ret;
        }


        /// <summary>
        /// 获取任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="picCount"></param>
        /// <param name="picAreaCount"></param>
        /// <returns></returns>
        public List<TaskInfo> GetListTask(int userId)
        {
   
            List<TaskInfo> taskList = new List<TaskInfo>();
            if (userId != 0)
            {
                List<WorkOrderFlowList> result;

                //List<int> statusList = new List<int>();
                //statusList.Add((int)OrderFlowListStatus.Complete);
                //statusList.Add((int)OrderFlowListStatus.Error);
                //statusList.Add((int)OrderFlowListStatus.UnProduct);
                using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
                {
                    //result = DataEntites.WorkOrderFlowList.Where(wl => wl.UserId == userId).ToList().Where(wlf => !statusList.Contains(wlf.Status)).ToList();
                    result = DataEntites.WorkOrderFlowList.Where(wl => wl.UserId == userId && wl.Status == (int)OrderFlowListStatus.Useable&&wl.tb_Tech.TechType ==(int)TechType.Factory).ToList();
                    foreach (var wofl in result)
                    {
                        #region 数据加载
                        if (!wofl.orderInfoReference.IsLoaded)
                        {
                            wofl.orderInfoReference.Load();
                        }

                        if (wofl.orderInfo.status != (int)OrderInfoStatus.Doing)
                        {
                            continue;
                        }

                        if (!wofl.orderInfo.Tb_OrderBagReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_OrderBagReference.Load();
                        }
                        if (!wofl.orderInfo.Tb_ProductReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_ProductReference.Load();
                        }
                        if (!wofl.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_OrderBag.ShopReference.Load();
                        }
                        if (!wofl.tb_TechReference.IsLoaded)
                        {
                            wofl.tb_TechReference.Load();
                        }
                        if (!wofl.orderInfo.photoInfo.IsLoaded)
                        {
                            wofl.orderInfo.photoInfo.Load();
                        }
                        #endregion

                        TaskInfo ti = new TaskInfo()
                        {
                            OrderProductId = wofl.orderInfo.OrderProductId,
                            CtmName = wofl.orderInfo.CtmName,
                            OrderProductName = wofl.orderInfo.OrderProductName,
                            OrderProductCode = wofl.orderInfo.OrderProductCode,
                            ProductNum = wofl.orderInfo.productNum,
                            Priority = (int)wofl.orderInfo.Priority,
                            ShopName = wofl.orderInfo.Tb_OrderBag.Shop.shopName,
                            ShopId = wofl.orderInfo.Tb_OrderBag.Shop.ShopId,
                            status = wofl.Status,
                            PageNum = wofl.orderInfo.photoInfo.Count,
                            ProductName = wofl.orderInfo.Tb_Product.ProductName,
                            ProductSize = wofl.orderInfo.Tb_Product.Width.ToString() + "*" + wofl.orderInfo.Tb_Product.Height.ToString(),
                            ProductRemark = wofl.orderInfo.Remark,
                            TechId = wofl.tb_Tech.TechId,
                            TechName = wofl.tb_Tech.TechName,
                            IsDeisgnTech = wofl.tb_Tech.IsDesign,
                            IsRebackOrder = false,
                            OrderPath = wofl.orderInfo.OrderPath
                        };
                        taskList.Add(ti);
                    }
                }
            }
            taskList = taskList.OrderByDescending(t => t.Priority).ToList();
            return taskList;
        }

        /// <summary>
        /// 根据产品Id获得任务
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public TaskInfo GetTask(string orderProductCode)
        {
            TaskInfo task =null;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                WorkOrderFlowList wofl = db.WorkOrderFlowList.FirstOrDefault(wl => wl.orderInfo.OrderProductCode == orderProductCode && wl.Status == 1);

                #region 数据加载
                if (!wofl.orderInfoReference.IsLoaded)
                {
                    wofl.orderInfoReference.Load();
                }
                if (!wofl.orderInfo.Tb_OrderBagReference.IsLoaded)
                {
                    wofl.orderInfo.Tb_OrderBagReference.Load();
                }
                if (!wofl.orderInfo.Tb_ProductReference.IsLoaded)
                {
                    wofl.orderInfo.Tb_ProductReference.Load();
                }
                if (!wofl.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                {
                    wofl.orderInfo.Tb_OrderBag.ShopReference.Load();
                }
                if (!wofl.tb_TechReference.IsLoaded)
                {
                    wofl.tb_TechReference.Load();
                }
                if (!wofl.orderInfo.photoInfo.IsLoaded)
                {
                    wofl.orderInfo.photoInfo.Load();
                }
                #endregion

                task = new TaskInfo()
                {
                    OrderProductId = wofl.orderInfo.OrderProductId,
                    CtmName = wofl.orderInfo.CtmName,
                    OrderProductName = wofl.orderInfo.OrderProductName,
                    ProductNum = wofl.orderInfo.productNum,
                    Priority = (int)wofl.orderInfo.Priority,
                    ShopName = wofl.orderInfo.Tb_OrderBag.Shop.shopName,
                    ShopId = wofl.orderInfo.Tb_OrderBag.Shop.ShopId,
                    status = wofl.Status,
                    PageNum = wofl.orderInfo.photoInfo.Count,
                    ProductName = wofl.orderInfo.Tb_Product.ProductName,
                    ProductSize = wofl.orderInfo.Tb_Product.Width.ToString() + "*" + wofl.orderInfo.Tb_Product.Height.ToString(),
                    ProductRemark = wofl.orderInfo.Remark,
                    TechId = wofl.tb_Tech.TechId,
                    TechName = wofl.tb_Tech.TechName,
                    IsDeisgnTech = wofl.tb_Tech.IsDesign,
                    IsRebackOrder = false,
                    OrderPath = wofl.orderInfo.OrderPath
                };
            }
            return task;
        }

        public DataTable GetPrintInfo(string barcode)
        {
            return _dal.GetPrintInfo(barcode);
        }

        public string GetProductCodeByPhotoID(int photoID)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                photoInfo ph = db.photoInfo.FirstOrDefault(p => p.photoId == photoID);
                if (ph == null)
                {
                    return "";
                }
                else
                {
                    ph.orderInfoReference.Load();
                    return ph.orderInfo.OrderProductCode;
                }
            }
        }

        public List<TaskInfo> GetListTask(List<int> Task)
        {
            int ablestate = (int)OrderFlowListStatus.Useable;
            List<TaskInfo> taskList = new List<TaskInfo>();
            if (Task.Count > 0)
            {
                List<WorkOrderFlowList> result;

                //List<int> statusList = new List<int>();
                //statusList.Add((int)OrderFlowListStatus.Complete);
                //statusList.Add((int)OrderFlowListStatus.Error);
                //statusList.Add((int)OrderFlowListStatus.UnProduct);
                using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
                {
                    //result = DataEntites.WorkOrderFlowList.Where(wl => wl.UserId == userId).ToList().Where(wlf => !statusList.Contains(wlf.Status)).ToList();
                    result = DataEntites.WorkOrderFlowList.Where(wl => Task.Contains(wl.tb_Tech.TechId) && wl.Status == ablestate && wl.tb_Tech.TechType == (int)TechType.Factory).ToList();
                    foreach (var wofl in result)
                    {
                        #region 数据加载
                        if (!wofl.orderInfoReference.IsLoaded)
                        {
                            wofl.orderInfoReference.Load();
                        }

                        if (wofl.orderInfo.status != (int)OrderInfoStatus.Doing)
                        {
                            continue;
                        }

                        if (!wofl.orderInfo.Tb_OrderBagReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_OrderBagReference.Load();
                        }
                        if (!wofl.orderInfo.Tb_ProductReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_ProductReference.Load();
                        }
                        if (!wofl.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_OrderBag.ShopReference.Load();
                        }
                        if (!wofl.tb_TechReference.IsLoaded)
                        {
                            wofl.tb_TechReference.Load();
                        }
                        if (!wofl.orderInfo.photoInfo.IsLoaded)
                        {
                            wofl.orderInfo.photoInfo.Load();
                        }
                        #endregion

                        TaskInfo ti = new TaskInfo()
                        {
                            OrderProductId = wofl.orderInfo.OrderProductId,
                            CtmName = wofl.orderInfo.CtmName,
                            OrderProductName = wofl.orderInfo.OrderProductName,
                            OrderProductCode = wofl.orderInfo.OrderProductCode,
                            ProductNum = wofl.orderInfo.productNum,
                            Priority = (int)wofl.orderInfo.Priority,
                            ShopName = wofl.orderInfo.Tb_OrderBag.Shop.shopName,
                            ShopId = wofl.orderInfo.Tb_OrderBag.Shop.ShopId,
                            status = wofl.Status,
                            PageNum = wofl.orderInfo.photoInfo.Count,
                            ProductName = wofl.orderInfo.Tb_Product.ProductName,
                            ProductSize = wofl.orderInfo.Tb_Product.Width.ToString() + "*" + wofl.orderInfo.Tb_Product.Height.ToString(),
                            ProductRemark = wofl.orderInfo.Remark,
                            TechId = wofl.tb_Tech.TechId,
                            TechName = wofl.tb_Tech.TechName,
                            IsDeisgnTech = wofl.tb_Tech.IsDesign,
                            IsRebackOrder = false,
                            OrderPath = wofl.orderInfo.OrderPath
                        };
                        taskList.Add(ti);
                    }
                }
            }
            taskList = taskList.OrderByDescending(t => t.Priority).ToList();
            return taskList;
        }
    }
}
